/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.lps.client.controller;

import com.lps.action.LoginAction;
import com.lps.client.Client;
import com.lps.client.view.MainFrame;
import com.lps.response.LoginResponse;
import com.lps.response.Response;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

/**
 *
 * @author thetrungbk
 */
public class LoginController implements ActionListener {

    private JFrame frame;
    private JTextField txtUsername;
    private JTextField txtPassword;
    /**
     * Constructor
     * @param frame
     * @param txtUsername
     * @param txtPassword
     */
    public LoginController(JFrame frame, JTextField txtUsername, JTextField txtPassword) {
        this.frame = frame;
        this.txtUsername = txtUsername;
        this.txtPassword = txtPassword;
    }
    /**
     * Login action performed
     * @param e
     */
    public void actionPerformed(ActionEvent e) {
        String user = txtUsername.getText();
        String password = txtPassword.getText();
        LoginAction action = new LoginAction();
        action.setUsername(user);
        action.setPassword(password);
        login(action);
    }
    /**
     * Do login
     * @param loginAction
     */
    public void login(LoginAction loginAction) {
        try {
            Response defaultResponse = Client.getInstance().sendAction(loginAction);
            if (defaultResponse.getCode() == Response.FAIL) {
                JOptionPane.showMessageDialog(frame, defaultResponse.getMessage(), "Error ", JOptionPane.ERROR_MESSAGE);
                return;
            } else if (defaultResponse.getCode() == Response.OK) {
                LoginResponse response = (LoginResponse) defaultResponse;
                System.out.println("Client [doLogin]: OK");
                Client.getInstance().setCurrentUser(response.getUser());
                Client.getInstance().setSessionId(response.getSessionId());
                frame.setVisible(false);
                (new MainFrame()).setVisible(true);
                //System.out.println("User Type :"+response.getUser().getDepartment());
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(frame, ex.getMessage(), "Error " + ex, JOptionPane.ERROR_MESSAGE);
            ex.printStackTrace();
        }
    }
}
